import base64
import random

from django.conf import settings
from django.core.mail import send_mail

from dadashop.celery import app
from django.core.cache import caches

from utils.sms import SMS

CODE_CACHE = caches['default']


@app.task
def async_send_activation_email(email, uname):
    code_num = random.randint(1000, 9999)
    code = f"{code_num}_{uname}"
    code = base64.urlsafe_b64encode(code.encode()).decode()
    active_url = f"http://127.0.0.1:7000/dadashop/templates/active.html?code={code}"
    message = f"""
    {uname}
    <p>Welcome to DadaShop!</p>
    <p><a href='{active_url}'>Click here to activate your account</a></p>
    """
    send_mail(
        subject='DadaShop Account Activation',
        message='',
        from_email=settings.EMAIL_HOST_USER,
        recipient_list=[email],
        html_message=message,
        fail_silently=False
    )
    CODE_CACHE.set(f'email_active_{uname}', code_num, timeout=60 * 60 * 24)

@app.task
def async_send_message(phone,code):
    sms=SMS(**settings.SMS_CONFIG)
    sms.send_sms(phone,code)